import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:novel_reader/utils/utils.dart';

class BackHandler {
  final _delaySeconds = 2;
  DateTime? _lastBackPressedTime;
  final State _state;

  BackHandler(this._state);

  void handleBackPressed(bool didPop) {
    if (!didPop) {
      if (ModalRoute.of(_state.context)?.isCurrent == false) {
        Navigator.of(_state.context).pop();
        return;
      }
      final now = DateTime.now();
      if (_lastBackPressedTime == null ||
          now.difference(_lastBackPressedTime!) >
              Duration(seconds: _delaySeconds)) {
        _lastBackPressedTime = now;

        Utils.showToast(_state.context, '再按一次退出应用');
        return;
      }
      if (_state.mounted) {
        SystemNavigator.pop();
      }
    }
  }
}
